<?php

/**
* @copyright   (C) 2010 iJoomla, Inc. - All rights reserved.
* @license  GNU General Public License, version 2 (http://www.gnu.org/licenses/gpl-2.0.html) 
* @author  iJoomla.com webmaster@ijoomla.com
* @url   http://www.ijoomla.com/licensing/
* the PHP code portions are distributed under the GPL license. If not otherwise stated, all images, manuals, cascading style sheets, and included JavaScript  
* are NOT GPL, and are released under the IJOOMLA Proprietary Use License v1.0 
* More info at http://www.ijoomla.com/licensing/
*/

defined('_JEXEC') or die('Restricted access');
	
class QuestionDateTime{
	
	function QuestionDateTime(){
	}
	
	function display($orientation = "", $question_id, $survey_id, $params, $question_details, $completed, $session_id){	
		$return_content_array = array();	
		$return = "";
		$answer = "";
		$question_class = isset($params->question)? $params->question : "";
		$question_description = isset($params->question_description)? $params->question_description : "";		
		$javascript = "";
		$entered = "";
		$row_class = $params->table_row2;
		$row_class_ok = "true";
		$answers = $this->getAnswers($question_id);
		$validation = "";		
		
		$return .= '<table width="100%" class="table_question">';
		$return .= 	  '<tr>';
		$return .= 	  	 '<td class="'.$question_class.'">';
		$return .=           $question_details["0"]["title"];
		if($question_details["0"]["required"] == "1"){
			$return .= '<span class="question_required"> *</span>';
			$javascript = ' onchange="setentertext(form.q'.$question_id.', this)" ';								
		}
		$validation = $this->createValidation($answers, $question_id, $question_details["0"]["title"], $question_details["0"]["required"]);	
		$return .= 	  	 '</td>';
		$return .= 	  '</tr>';
		if($question_details["0"]["description"] != ""){
			$return .='<tr>';
			$return .= 	 '<td class="'.$question_class.'">';
			$return .=       $question_details["0"]["description"];
			$return .= 	 '</td>';
			$return .='</tr>';
		}
		$return .= 	  '<tr>';
		$return .= 	  	 '<td class="'.$question_class.'">';
		
		$return .= 			'<table width="100%">';		
		$return .= 	  			'<tr>';
		$return .= 	     			'<td>';
		$return .= 	         			'<input type="hidden" value="datetime" name="question['.$question_id.'][type]">';
    	$return .= 	         			'<input type="hidden" value="open" name="question['.$question_id.'][orientation]">';
		$return .= 	     			'</td>';
		//create table header with yyyy-dd-mm or another order
		$return .= $this->getDateColumns($params);
		//create table content
		if(isset($answers) && count($answers)>0){
			foreach($answers as $key=>$value){				
				$return .= 	    '<tr>';
					$return .= 	    '<td><span class="'.$params->answer.'">'.trim($value["value"]).'</span></td>';
					$return .= $this->getRows($params, $question_id, $value, $session_id);
				$return .= 	    '</tr>';				    
			}
		}
		$return .= 			'</table>';		
		$return .= 	  	 '</td>';
		$return .= 	  '</tr>';
		$return .= '</table>';				
		$return .= '<input type="hidden" id="q'.$question_id.'" name="q'.$question_id.'" value="'.$entered.'">';
		$return .= '<input type="hidden" id="qtext'.$question_id.'" name="qtext'.$question_id.'" value="'.$value.'">';
		$return .= '<input type="hidden" name="classes['.$question_id.']" value="QuestionDateTime">';		
		
		$return_content_array["content"] = $return;
		$return_content_array["validation"] = $validation;
		
		return $return_content_array;
	}
	
	function getRows($params, $question_id, $value, $session_id){
		$return = "";
		$year = "";
		$mount = "";
		$day = "";
				
		if(isset($_SESSION["view_result"]) && $_SESSION["view_result"]=="true"){
			$database_values = $this->getValue($question_id, $session_id);		
			if(is_array($database_values) && count($database_values)>0){
				foreach($database_values as $key=>$data_val){
					if($data_val["a_id"] == $value["id"]){
						$year = date('Y', $data_val["value"]);
						$mount = date('n', $data_val["value"]);
       	 				$day = date('j', $data_val["value"]);
						break;
					}
				}
			}
		}		
		
		switch($params->general_date){
			case "1" : {
				$return .= '<td><input type="text" class="" size="6" id="am'.$value["id"].'" value="'.$mount.'" name="question['.$question_id.'][answer]['.$value["id"].'][month]"></td>';
				$return .= '<td><input type="text" class="" size="4" id="ad'.$value["id"].'" value="'.$day.'" name="question['.$question_id.'][answer]['.$value["id"].'][day]"></td>';
				$return .= '<td><input type="text" class="" size="4" o="" id="ay'.$value["id"].'" value="'.$year.'" name="question['.$question_id.'][answer]['.$value["id"].'][year]"></td>';
				break;
			}
			case "2" : {
				$return .= '<td><input type="text" class="" size="4" id="ad'.$value["id"].'" value="'.$day.'" name="question['.$question_id.'][answer]['.$value["id"].'][day]"></td>';
				$return .= '<td><input type="text" class="" size="6" id="am'.$value["id"].'" value="'.$mount.'" name="question['.$question_id.'][answer]['.$value["id"].'][month]"></td>';				
				$return .= '<td><input type="text" class="" size="4" o="" id="ay'.$value["id"].'" value="'.$year.'" name="question['.$question_id.'][answer]['.$value["id"].'][year]"></td>';
				break;
			}
			case "3" : {
				$return .= '<td><input type="text" class="" size="4" o="" id="ay'.$value["id"].'" value="'.$year.'" name="question['.$question_id.'][answer]['.$value["id"].'][year]"></td>';
				$return .= '<td><input type="text" class="" size="6" id="am'.$value["id"].'" value="'.$mount.'" name="question['.$question_id.'][answer]['.$value["id"].'][month]"></td>';
				$return .= '<td><input type="text" class="" size="4" id="ad'.$value["id"].'" value="'.$day.'" name="question['.$question_id.'][answer]['.$value["id"].'][day]"></td>';												
				break;
			}
			case "4" : {
				$return .= '<td><input type="text" class="" size="4" o="" id="ay'.$value["id"].'" value="'.$year.'" name="question['.$question_id.'][answer]['.$value["id"].'][year]"></td>';
				$return .= '<td><input type="text" class="" size="4" id="ad'.$value["id"].'" value="'.$day.'" name="question['.$question_id.'][answer]['.$value["id"].'][day]"></td>';
				$return .= '<td><input type="text" class="" size="6" id="am'.$value["id"].'" value="'.$mount.'" name="question['.$question_id.'][answer]['.$value["id"].'][month]"></td>';				
				break;
			}
		}
		return $return;
	}
	
	function getDateColumns($params){
		$return = "";
		switch($params->general_date){
			case "1" : {
				$return = '<td>MM</td> <td>DD</td> <td>YYYY</td>';
				break;
			}
			case "2" : {
				$return = '<td>DD</td> <td>MM</td> <td>YYYY</td>';
				break;
			}
			case "3" : {
				$return = '<td>YYYY</td> <td>MM</td> <td>DD</td>';
				break;
			}
			case "4" : {
				$return = '<td>YYYY</td> <td>DD</td> <td>MM</td>';
				break;
			}
		}
		return $return;
	}
	
	function getAnswers($question_id){
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('id, value');
		$query->from('#__ijoomla_surveys_answers');
		$query->where("question_id=".intval($question_id));	
		$query->order("id asc");	
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();	
		return $result;
	}	
	
	function getValue($question_id, $session_id){
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('*');
		$query->from('#__ijoomla_surveys_result');
		$query->where("q_id=".intval($question_id)." and session_id=".intval($session_id));		
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();		
		return $result;
	}
	
	function createValidation($answers, $question_id, $title, $required){
		$result = "";
		if($required == 1){
			$result .= "	var rq".$question_id."='required';"."\n";
		}
		else{
			$result .= "	var rq".$question_id."='none';"."\n";
		}
		foreach($answers as $key=>$value){
			$result .= "	if((document.survey_content.am".$value["id"].".value!='' || document.survey_content.ad".$value["id"].".value!='' || document.survey_content.ay".$value["id"].".value!='' || rq".$question_id."=='required')){"."\n".
							"		if(checkNumber(document.survey_content.am".$value["id"].", 1, 2, 1, 12, 'You must enter the month (1-12)') == false || checkNumber(document.survey_content.ad".$value["id"].", 1, 2, 1, 31, 'You must enter the day (1-31)') == false || checkNumberYear(document.survey_content.ay".$value["id"].", 4, 4, 0, 0, 'You must enter the year') == false){"."\n".
							"			return false;"."\n".
							"		}"."\n".
						"	}\n";	
		}		
		return $result;
	}
	
	function save($id, $type, $session_id){			
		$db =& JFactory::getDBO();		
		$all_answers = JRequest::getVar("question");					
		$answers = $all_answers[$id]["answer"];													
		
		if($this->answerExist($id, $session_id)){
			$sql = "delete from  #__ijoomla_surveys_result where q_id=".$id." and session_id=".$session_id;												
			$db->setQuery($sql);
			$db->query();
		}		
		foreach($answers as $key=>$value){	
			if(trim($value["month"]) != "" && trim($value["day"]) != "" && trim($value["year"]) != ""){																
				$date = mktime(0, 0, 0, $value["month"], $value["day"], $value["year"]);						
				$sql = "insert into #__ijoomla_surveys_result(`q_id`, `a_id`, `m_id`, `ac_id`, `session_id`, `value`) values (";					
				$sql .= $id.", ".$key.", 0, 0, ".$session_id.", ".$date;
				$sql .= ")";										
				$db->setQuery($sql);
				$db->query();
			}
		}
	}	
	
	function answerExist($question_id, $session_id){
		$db =& JFactory::getDBO();
		$sql = "select count(*) from #__ijoomla_surveys_result where q_id=".$question_id." and session_id=".$session_id;
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();
		if($result != "0"){
			return true;
		}
		return false;
	}
	
	function editResult($id, $survey_id, $params, $i, $title, $all_responses_count){
		$answers = $this->getAnswers($id);
		$controller = JRequest::getVar("controller", "", "get");		
		
		$return  = '<table width="100%" style="border:1px solid #CCCCCC; border-collapse:collapse;">';
		$return .= 		'<tr>';
		$return .= 			'<td class="'.$params->question.'" colspan="4" style="padding-left:5px;">';
		$return .= 				'<b>'.$i.". ".$title.'</b>';
		$return .= 			'</td>';
		$return .= 		'</tr>';
		$return .= 		'<tr>';
		$return .= 			'<td></td>';
		$return .= 			'<td></td>';
		$return .= 			'<td align="center">';
		$return .= 				JText::_("COM_SURVEYS_RESPONSE_PERCENT");
		$return .= 			'</td>';
		$return .= 			'<td align="center">';
		$return .= 				JText::_("COM_SURVEYS_TOTAL_RESPONSE");	
		$return .= 			'</td>';				
		$return .= 		'</tr>';
		$k = 0;

		foreach($answers as $a_key=>$a_value){
			$class = $params->table_row1;
			if($k%2 != 0){
				$class = $params->table_row2;
			}
			$k++;
			$count 	 = $this->countTotal($a_value["id"]);
			$return .= '<tr class="'.$class.'">';
			$return .= 		'<td align="right" style="padding-right:5px;">';
			$app =& JFactory::getApplication();      	
			if($app->isAdmin()){
				if($controller != "" && $controller == "statistics"){
					$r_id = JRequest::getVar("r_id", "0");
					$link = JURI::root().'administrator/index.php?option=com_surveys&controller=editdetails&task=edit_details&q_id='.$id.'&a_id='.$a_value["id"]."&r_id=".$r_id;
					$return .= '<a style="text-decoration:none;" href="'.$link.'">'.JText::_("COM_SURVEYS_VIEW_DETAIL").'</a>'."&nbsp;&nbsp;";
				}				
			}
			else{	
				$link = JRoute::_('index.php?option=com_surveys&controller=editsurvey&Itemid='.JRequest::getVar("Itemid").'&task=edit_details&q_id='.$id.'&a_id='.$a_value["id"]);
				$return .= '<a style="text-decoration:none;" href="'.$link.'">'.JText::_("COM_SURVEYS_VIEW_DETAIL").'</a>'."&nbsp;&nbsp;";
			}
			$return .= 			$a_value["value"];
			$return .= 		'</td>';			
			$return .= 		'<td align="left" width="30%">';
			$return .= 		@$this->getPicture(number_format( (($count * 100) / $all_responses_count), 2, '.', '') );
			$return .= 		'</td>';
			$return .= 		'<td align="center">';			
			$return .= 		@number_format( (($count * 100) / $all_responses_count), 2, '.', ''). " %";
			$return .= 		'</td>';
			$return .= 		'<td align="center">';
			$return .= 			$count;
			$return .= 		'</td>';				
			$return .= '</tr>';	
		}
		$return .= 		'<tr>';
		$return .= 			'<td colspan="3" style="padding-right:5px;" align="right">';
		$return .= 				'<b>'.JTExt::_("COM_SURVEYS_TOTAL_RESPONDENTS").':</b>';
		$return .= 			'</td>';
		$return .= 			'<td class="'.$params->total_background.'" align="center">';
		$return .= 				'<b>'.$this->countPerQuestion($id).'</b>';
		$return .= 			'</td>';
		$return .= 		'</tr>';
		$return .= '</table>';
		return $return;		
	}	
		
	function countTotal($a_id){
		$r_id = JRequest::getVar("r_id", "");
		$and = "";
		if($r_id != ""){
			$and = " and session_id=".$r_id;
		}
		$db =& JFactory::getDBO();		
		$sql = "select count(*) from #__ijoomla_surveys_result where a_id=".$a_id.$and;		
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadResult();
		return $result;
	}
	
	function countPerQuestion($id){
		$r_id = JRequest::getVar("r_id", "");
		$and = "";
		if($r_id != ""){
			$and = " and session_id=".$r_id;
		}
		$db =& JFactory::getDBO();		
		$sql = "select count(*) from #__ijoomla_surveys_result where q_id=".$id.$and." group by session_id";		
		$db->setQuery($sql);
		$db->query();
		$result = $db->loadAssocList();
		return count($result);
	}
	
	function getPicture($value){	
	    $picture = "";
		$picture .= "<div style=\"width:100%;\">";
		$picture .= 	"<div style=\"width:" . $value . "%; background-color:#0000CC;\"> &nbsp; ";
		$picture .= 	"</div>";
		$picture .= "</div>";
		return $picture;
	}
	
	function getForHeader($id, $title){		
		return $title;
	}
	
	function getForRow($q_id, $sess_id){
		$answers = $this->getAnswers($q_id);
		$result_array = array();
		
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('sr.value as result_value, a.value as answer_value');
		$query->from('#__ijoomla_surveys_result sr, #__ijoomla_surveys_answers a');
		$query->where("sr.q_id=".intval($q_id)." and sr.session_id=".intval($sess_id)." and sr.a_id=a.id");		
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();
		if($result == NULL || count($result) == 0){
			return "NO ANSWER";
		}
		else{
			foreach($result as $key=>$value){
				$result_array[] = trim($value["answer_value"])." - ". date("j-m-Y H:i", $value["result_value"]);
			} 
		}
		return implode(" AND ", $result_array);
	}
	
	function getQuestionResultForEmail($q_id, $session_id, $title){		
		$return = $title.":"."\n";
		
		$db =& JFactory::getDBO();		
		$query = $db->getQuery(true);
		$query->clear();		
		$query->select('sr.value as result_value, a.value as answer_value');
		$query->from('#__ijoomla_surveys_result sr, #__ijoomla_surveys_answers a');
		$query->where("sr.q_id=".intval($q_id)." and sr.session_id=".intval($session_id)." and sr.a_id=a.id");		
		$db->setQuery($query);		
		$db->query();
		$result = $db->loadAssocList();
		
		foreach($result as $key=>$value){
			$return .= "\t".trim($value["answer_value"]).": ".date("j-m-Y", trim($value["result_value"]));
			$return .= "\n";
		}			
		return $return;
	}
	
	function checkCompleted($logic, $compare, $answer, $skip_answer){
		$return = false;		
		if($logic == "OR"){
			if($compare == "equal"){
				foreach($skip_answer as $key=>$value){
					if(isset($answer[$value])){
						$return = true;
						return $return;
					}
				}
			}
			elseif($compare == "different"){
				foreach($skip_answer as $key=>$value){
					if(isset($answer[$value])){
						$return = false;
						return $return;
					}
				}
				$return = true;
				return $return;
			}
		}
		elseif($logic == "AND"){
			if($compare == "equal"){
				foreach($skip_answer as $key=>$value){
					if(!isset($answer[$value])){
						$return = false;
						return $return;						
					}
				}
				$return = true;
				return $return;
			}
			elseif($compare == "different"){
				foreach($answer as $key=>$value){
					if(in_array($value, $skip_answer)){
						$return = false;
						return $return;						
					}
				}
				$return = true;
				return $return;
			}
		}			
	}
			
};

?>
